package leetcode.code1655;

import java.util.HashMap;
import java.util.Map;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	int range;
	int ok;
	int help[];
	int[] group;

	public boolean canDistribute(int[] nums, int[] quantity) {
		Map<Integer, Integer> cnts = new HashMap<>();
		for (int num : nums) {
			cnts.put(num, cnts.getOrDefault(num, 0) + 1);
		}
		this.range = cnts.size();
		int n = quantity.length;
		ok = (1 << n) - 1;
		group = new int[this.range];
		int idx = 0;
		for (Map.Entry<Integer, Integer> entry : cnts.entrySet()) {
			group[idx] = entry.getValue();
			idx++;
		}
		this.help = new int[1 << n];
		for (int i = 1; i < 1 << n; i++) {
			for (int j = 0; j < n; j++) {
				if (((1 << j) & i) != 0) {
					help[i] += quantity[j];
				}
			}
		}
		Boolean[][] dp = new Boolean[this.range][1<<n];
		return f(0, 0,dp);
	}

	private boolean f(int idx, int satisfy,Boolean[][] dp) {
		if (satisfy == ok) {
			return true;
		}
		if (idx == range) {
			return false;
		}
		if(dp[idx][satisfy]!=null) {
			return dp[idx][satisfy];
		}
		int diff = satisfy ^ ok;
		int _enum = diff;
		int cur = group[idx];
		while (_enum != 0) {
			if (help[_enum] <= cur) {
				if (f(idx + 1, satisfy | _enum,dp)) {
					return true;
				}
			}
			_enum = diff & (_enum - 1);
		}
		if (f(idx + 1, satisfy,dp)) {
			return true;
		}
		dp[idx][satisfy] = false;
		return false;
	}

	@Override
	public void debug4() {
		H.compare(false, this.canDistribute(H.str2array3("[1,2,3,4]"), H.str2array3("[2]")));
		H.compare(true, this.canDistribute(H.str2array3("[1,2,3,3]"), H.str2array3("[2]")));
		H.compare(true, this.canDistribute(H.str2array3("[1,1,2,2]"), H.str2array3("[2,2]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
